import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-16
 * Time: 15:46
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }
    public void start(){
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);      //自动把他转换成字符，方便构造客户端使用
            PrintWriter writer = new PrintWriter(outputStream); //自动转换成字节， 方便发送数据给服务器
            while(true){    //从控制器读取请求， 发送给服务器
                //1.从控制台读取用户输入
                String request = scanner.next();
                //2.发送给服务器
                writer.println(request);
                //刷新缓冲区到网卡中， 才会真正发送
                writer.flush();
                //3.读取服务器的响应
                String response = scannerNet.next();
                //4.打印到控制台
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
